package edu.fpa.day0806;

public class CoTest {

    public static void main(String[] args) {
        SynContainer syn =new SynContainer();
        Productor p = new Productor(syn);
        Consumer c = new Consumer(syn);
        p.start();
        c.start();

    }

}
class Productor extends Thread{
    SynContainer syn = new SynContainer();

    public Productor(SynContainer syn) {
        this.syn = syn;
    }
    @Override
    public void run() {
        for(int i=1;i<100;i++) {
            System.out.println("生产"+i+"个馒头");
            syn.push(new Steamedbun(i));

        }
    }

}
class Consumer extends Thread{
    SynContainer syn = new SynContainer();

    public Consumer(SynContainer syn) {
        super();
        this.syn = syn;
    }
    @Override
    public void run() {

        for(int i=1;i<1000;i++) {
            Steamedbun s = syn.pop();
            System.out.println("消费"+s.id+"个馒头");


        }
    }
}
class SynContainer{
    Steamedbun[] buns = new Steamedbun[10];
    int count = 0;


    public synchronized void push(Steamedbun bun) {
        if(count==buns.length) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        buns[count++] = bun;
        this.notifyAll();
    }


    public synchronized Steamedbun pop() {
        if(count==0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        count--;
        this.notifyAll();
        return buns[count];

    }
}
class Steamedbun{
    int id;

    public Steamedbun(int id) {
        super();
        this.id = id;
    }

}